/**
 * @module creep数量控制模块
 */
import {BUILDER, DEFENDER, ENDER} from "../constant/roleConstant.js";
import {creatCreep, creepNum, getSortedRolesByWeight} from "../config/creepNum/creepNumCore.js";
import {countOccurrences} from "../utils.js";


/**
 * @description creep数量控制器
 */
export const creepNumController = (roomKey) => {
    deleteDeadCreep()
    const spawns = Memory.Rooms[roomKey].spawns.map((id) => Game.getObjectById(id))
    for (const spawn of spawns) {
        // const spawn = Game.spawns[name]
        if (!spawn.spawning) {
            creepNumJudge(spawn, roomKey)
        }
    }

}
/**
 * 生成creep核心判断逻辑
 * @param {StructureSpawn} spawn
 * @param {string} roomKey
 */
const creepNumJudge = (spawn, roomKey) => {
    //1.根据权重信息组成role的列表通过权重排序
    const role_list = getSortedRolesByWeight(roomKey, DEFENDER, ENDER)
    //2.遍历新组装的角色信息
    for (const role of role_list) {
        //针对builder的特殊判断条件
        if (role === BUILDER) {
            if (judge(role, roomKey) && Game.rooms[roomKey].find(FIND_CONSTRUCTION_SITES).length !== 0) {
                creatCreep(spawn, roomKey, role)
                return;
            }
        } else {
            if (judge(role, roomKey)) {
                creatCreep(spawn, roomKey, role)
                return;
            }
        }
    }
}
/**
 * @description 判断数量是否满足生成creep的条件
 * @param {string} role
 * @param {string} roomKey
 * @returns {boolean}
 */
export const judge = (role, roomKey) => {
    return countOccurrences(getRoleList(roomKey), role) < creepNum(role, roomKey)
}

/**
 *@description 删除内存中死亡的creep
 */
const deleteDeadCreep = () => {
    for (let name in Memory.creeps) {
        if (!Game.creeps[name]) {
            delete Memory.creeps[name]
        }
    }
}

/**
 * @description 获取内存中存活的creep的角色
 * @returns {string[]}
 */
const getRoleList = (roomKey) => {
    deleteDeadCreep()
    /**
     * @description 角色列表
     * @type {string[]}
     */
    const roleList = []
    for (const creep of Game.rooms[roomKey].find(FIND_MY_CREEPS)) {
        roleList.push(creep.memory.role)
    }

    return roleList
}